package com.bwie.gddproject.login.precenter;

import android.text.TextUtils;

import com.bwie.gddproject.login.model.ILoginModel;
import com.bwie.gddproject.login.model.LoginBean;
import com.bwie.gddproject.login.model.LoginModel;
import com.bwie.gddproject.login.view.ILoginActivity;
import com.bwie.gddproject.net.OnNetLitenner;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 我走路带风 on 2017/11/8.
 */

public class LoginPresenter {
    private ILoginActivity loginActivity;
    private ILoginModel loginModel;

    public LoginPresenter(ILoginActivity loginActivity) {
        this.loginActivity = loginActivity;
        loginModel  = new LoginModel();
    }

    public void login(){
        String account = loginActivity.getAccount();
        String pwd = loginActivity.getPwd();
        if (checkAccount(account)&&checkPwd(pwd)){

            loginModel.login(account, pwd, new OnNetLitenner<LoginBean>() {
                @Override
                public void success(LoginBean loginBean) {
                    if (loginBean.getCode().equals("0")){
                        loginActivity.saveByShared();
                        loginActivity.show(loginBean.getMsg());
                        loginActivity.toIndexAc(loginBean);
                        loginActivity.finishThis();
                    }else{
                        loginActivity.show(loginBean.getMsg());

                    }

                }

                @Override
                public void fail(String errer) {
                    loginActivity.show("登录失败");
                }
            });
        }
    }

    private boolean checkPwd(String pwd) {
        if (TextUtils.isEmpty(pwd)) {
            //给用户提示，输入的账号不能为空
            loginActivity.show("请输入密码");
            return false;
        }
        if (pwd.length() != 6) {
            loginActivity.show("请输入6位密码");
            return false;
        }
        return true;
    }
    /*
    判断是否是手机号
     */
    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-35-9]|17[6-8]|18[0-9])[0-9]{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    private boolean checkAccount(String account){

        if (TextUtils.isEmpty(account)){
            loginActivity.show("请输入账号");
            return false;
        }

        if (!isMobileNO(account)){
            loginActivity.show("请输入正确的手机号");
            return false;
        }

        return true;

    }
}
